import React from "react";
import RcPicker from "rc-picker";
import zhCN from "rc-picker/es/locale/zh_CN";
import generateConfig from "rc-picker/es/generate/dayjs";
import {
  Calendar as CalendarIcon,
  Delete as DeleteIcon,
  Dateright as DateRightIcon,
  Datedoubleright as DateDoubleRightIcon,
  Datedoubleleft as DateDoubleLeftIcon,
  Dateleft as DateLeftIcon,
} from "@ct0/icons";

import type { Dayjs } from "dayjs";
import type { DatePickerProps } from "./type";
import dayjs from "dayjs";
import { isNil, isUndefined } from "@ct0/functions";

export default function DatePicker({
  value: propsValue,
  defaultValue,
  picker,
  style,
  className,
  disabled,
  placeholder,
  onChange,
  disablePreviousDate,
  getPopupContainer,
}: DatePickerProps) {
  const showTime = picker == "datetime";
  const showToday = picker == "date";

  const defaultV = isUndefined(defaultValue) ? undefined : dayjs(defaultValue);
  const value = isNil(propsValue) ? undefined : dayjs(propsValue);

  const handleChange = (value: Dayjs | null, dateString: string) => {
    const [timestamp, timeString] = value
      ? [value.valueOf(), dateString]
      : [null, null];
    onChange?.(timestamp, timeString);
  };

  /**
   * 禁止选择今天之前的日期
   * @param {Dayjs} current 当前时间
   * @returns {boolean}
   */
  const disableDatePatterns = (current: Dayjs): boolean => {
    if (disablePreviousDate) {
      return current < dayjs().startOf("day");
    }
    return false;
  };

  const defaultPopupContainer = (node: HTMLElement) => node.parentElement!;

  return (
    <RcPicker<Dayjs>
      value={value}
      defaultValue={defaultV}
      disabled={disabled}
      prefixCls="ct0-picker"
      picker="date"
      className={className}
      style={style}
      generateConfig={generateConfig}
      locale={zhCN}
      allowClear
      showTime={showTime}
      showToday={showToday}
      onChange={handleChange}
      getPopupContainer={getPopupContainer || defaultPopupContainer}
      prevIcon={<DateLeftIcon />}
      superPrevIcon={<DateDoubleLeftIcon />}
      nextIcon={<DateRightIcon />}
      superNextIcon={<DateDoubleRightIcon />}
      suffixIcon={<CalendarIcon />}
      clearIcon={<DeleteIcon />}
      placeholder={placeholder || "请选择日期"}
      role="ct0-picker"
      disabledDate={disableDatePatterns}
    />
  );
}
